var db = require('../db/connect')
var jsonres = require('./jsonres')
var server = require('./../server/server.js')

const noAuth = [
    '/api/login',
    '/api/regist',
    '/api/sendverify',
    '/api/checkverify',
    '/api/checktask',
    '/api/userstate',
    '/api/updatetask',
    '/api/rowdata',
    '/api/logout',
    '/api/getuid'
];

server.use(function(req,res,next) {
    for (var i = 0; i < noAuth.length; ++i) {
        if (req.url.indexOf(noAuth[i]) === 0) {
            return next()
        }
    }
    if (req.url.indexOf('/api/') === 0) {
        if (req.session.u && req.session.p) {
            db.count('users',{mobile: req.session.u, pwd: req.session.p},function(err,c) {
                if (c === 0) {
                    res.send(jsonres(-2,'未登录',null))
                    res.end()
                } else {
                    next();
                }
            })
        } else {
            res.send(jsonres(-2,'未登录',null))
            res.end()
        }
    } else {
        next()
    }
})
